// <copyright file="DataTable.cs" company="YUIAsp.Net">
// Copyright (c) 2009 All Right Reserved
// </copyright>
// <author>raul popescu</author>
// <email>dev@yuiasp.net</email>
// <date>2009-01-30</date>
// <summary>YUIAsp.Net File</summary>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using YUIAspNet.Common;

#region Embedded resources definitions
[assembly: WebResource("YUIAspNet.DataTable.DataTable.js", "text/javascript")]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.datatable.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.datatable-core.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.datatable-skin.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.paginator-skin.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.dt-arrow-dn.png", "image/png")]
[assembly: WebResource("YUIAspNet.EmbeddedSkins.DefaultSkin.DataTable.dt-arrow-up.png", "image/png")]

#endregion

namespace YUIAspNet
{
    /// <summary>
    /// DataTable control.
    /// </summary>
    [ToolboxItem(true)]
    [ParseChildren(true)]
    public class DataTable : YUIScriptBaseControl, INamingContainer
    {
        Panel _dtContainer = new Panel();
        Paginator _paginator;
        GridView _grid;
        string _gridID;
        private IList<DataTableColumn> _columns;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataTable"/> class.
        /// </summary>
        public DataTable()
        {
            this.Init += new EventHandler(DataTable_Init);

            _dtContainer = new Panel();
            _dtContainer.ID = "dtContainer";

            _paginator = new Paginator();
            _paginator.AutoInitialize = false;

            EnableRowHover = true;
            EnableRowSelection = true;
        }

        void DataTable_Init(object sender, EventArgs e)
        {
            this.Controls.Add(_dtContainer);
            this.Controls.Add(_paginator);

            if (this.Parent != null && this._grid == null && this._gridID != null)
            {
                this._grid = this.Parent.FindControl(_gridID) as GridView;
            }
        }

        /// <summary>
        /// Registers the style sheets for the current control.
        /// Must be overriden in the parent control to add any css file reference.
        /// </summary>
        protected override void RegisterStyleSheets()
        {
            RegisterEmbeddedStylesheet("DataTable", "datatable-core.css");
            RegisterEmbeddedStylesheet("DataTable", "datatable-skin.css");

            if (ResultsPerPage > 0 && Paginator == null) // paging defined -> include paginator...
            {
                RegisterEmbeddedStylesheet("DataTable", "paginator-skin.css");
            }
        }

        /// <summary>
        /// Register the values to send to the client control for initialization.
        /// </summary>
        protected override void RegisterClientInitialization()
        {
            AddProperty("Container", _dtContainer.ClientID);
            if (Source != null)
                AddProperty("Source", Source.Serialize(), true);
            else if (_grid != null)
            {
                HtmlTableDataSource src = new HtmlTableDataSource();
                src.ElementID = this._grid.ClientID;
                this.Source = src;

                foreach (var col in Columns)
                {
                    src.AddColumn(col.Key);
                }

                AddProperty("Source", Source.Serialize(), true);
            }
            else throw new RequiredPropertyException("Source or Grid instance");

            AddProperty("Columns", Columns);
            if (!string.IsNullOrEmpty(Caption))
                AddProperty("Caption", Caption);
            AddProperty("DraggableColumns", DraggableColumns);
            AddProperty("DefaultSortOrder", (int)DefaultSortOrder);
            AddProperty("DefaultSortColumnKey", DefaultSortColumnKey);
            AddProperty("ResultsPerPage", ResultsPerPage);
            AddProperty("HidePaginator", HidePaginator);

            //width & height for scrolling
            AddProperty("Width", Width.ToString());
            AddProperty("Height", Height.ToString());

            AddProperty("EnableRowSelection", EnableRowSelection);
            AddProperty("EnableRowHover", EnableRowHover);

            AddProperty("PaginatorInstance", this.Paginator.ClientID);


            if (!string.IsNullOrEmpty(OnClientRowFormat))
            {
                AddProperty("OnRowFormat", OnClientRowFormat);
            }
        }

        /// <summary>
        /// Registers any additional scripts to include for this control.
        /// </summary>
        protected override void RegisterScriptReferences()
        {
            AddScriptReference(new ScriptReference("YUIAspNet.DataTable.DataTable.js", this.GetType().Assembly.FullName));
        }

        /// <summary>
        /// Attaches to an existing grid instance.
        /// </summary>
        /// <value>The attach to.</value>
        public string AttachedGridID
        {
            get { return _grid.ID; }
            set
            {
                if (this.Parent == null) // control not added to control tree... wait
                    this._gridID = value;
                else
                    this._grid = this.Parent.FindControl(value) as GridView;

            }
        }

        #region Public properties
        /// <summary>
        /// Gets or sets the source.
        /// </summary>
        /// <value>The source.</value>
        public DataSourceBase Source { get; set; }

        /// <summary>
        /// Gets or sets the caption.
        /// </summary>
        /// <value>The caption.</value>
        public string Caption { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the columns are draggable.
        /// </summary>
        /// <value><c>true</c> to enable draggable columns; otherwise, <c>false</c>.</value>
        public bool DraggableColumns { get; set; }

        /// <summary>
        /// If true, sorting and pagination are relegated to the DataSource for handling, using the request returned by the "generateRequest" function. Each new DataSource response blows away all previous Records. False by default, so sorting and pagination will be handled directly on the client side, without causing any new requests for data from the DataSource.
        /// </summary>
        /// <value><c>true</c> if dynamic data is enabled; otherwise, <c>false</c>.</value>
        public bool DynamicData { get; set; }

        /// <summary>
        /// Gets or sets the number format.
        /// </summary>
        /// <value>The number format.</value>
        public NumberFormat NumberFormat { get; set; }

        /// <summary>
        /// Gets or sets the date format.
        /// </summary>
        /// <value>The date format.</value>
        public DateFormat DateFormat { get; set; }

        /// <summary>
        /// Gets or sets the currency format.
        /// </summary>
        /// <value>The currency format.</value>
        public CurrencyFormat CurrencyFormat { get; set; }

        /// <summary>
        /// Gets or sets the default sort order.
        /// </summary>
        /// <value>The default sort order.</value>
        public SortDirection DefaultSortOrder { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether to hide the paginator.
        /// </summary>
        /// <value><c>true</c> if [hide paginator]; otherwise, <c>false</c>.</value>
        public bool HidePaginator { get; set; }

        /// <summary>
        /// Gets or sets the default sort column key.
        /// </summary>
        /// <value>The default sort column key.</value>
        public string DefaultSortColumnKey { get; set; }

        /// <summary>
        /// Gets or sets the results per page.
        /// </summary>
        /// <value>The results per page.</value>
        public int ResultsPerPage
        {
            get { return Paginator.RowsPerPage; }
            set { Paginator.RowsPerPage = value; }
        }

        /// <summary>
        /// Gets or sets the paginator.
        /// </summary>
        /// <value>The paginator.</value>
        public Paginator Paginator
        {
            get { return _paginator; }
        }

        /// <summary>
        /// Gets or sets the on client row format.
        /// </summary>
        /// <value>The on client row format.</value>
        public string OnClientRowFormat { get; set; }

        /// <summary>
        /// Gets or sets the columns.
        /// </summary>
        /// <value>The columns.</value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public IList<DataTableColumn> Columns 
        { 
            get
            {
                if(_columns == null)
                    _columns = new List<DataTableColumn>();
                return _columns;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to enable row hovering.
        /// </summary>
        public bool EnableRowHover { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether to enable row selection.
        /// </summary>
        public bool EnableRowSelection { get; set; }

        #endregion
    }
}
